package cn.edu.cqvie.atc.hash.link;

import java.math.BigInteger;

/**
 * 文件描述
 *
 * @author Zheng Shaohong
 */
public class HashTable {

    private LinkList[] arr;

    public HashTable() {
        this.arr = new LinkList[100];
    }

    public HashTable(LinkList[] arr) {
        this.arr = arr;
    }


    public HashTable(int maxSize) {
        this.arr = new LinkList[maxSize];
    }

    /**
     * 插入数据
     * @param info
     */
    public void insert(Info info) {
        // 获得关键字
        String key = info.getKey();
        // 关键字锁自定的哈希数
        int hashVal = hashCode(key);
        if (arr[hashVal] == null) {
            arr[hashVal] = new LinkList();
        }
        arr[hashVal].insertFirst(info);
    }

    /**
     * 查找数据
     * @param key
     * @return
     */
    public Info find(String key) {
        int hashVal = hashCode(key);
        Info info = (info = arr[hashVal].search(key).info) == null ? null : info;
        return info;
    }

    /**
     * 删除数据
     * @param key
     * @return
     */
    public Info delete(String key) {
        int hashVal = hashCode(key);
        Info info = (info = arr[hashVal].search(key).info) == null ? null : info;
        return info;
    }


    public int hashCode(String key) {
//        int hashVal = 0;
//        for (int i = key.length() - 1; i >= 0; i--) {
//            int letter = key.charAt(i) - 96;
//            hashVal += letter;
//        }
//        return hashVal;
        BigInteger hashVal = new BigInteger("0");
        BigInteger pow27 = new BigInteger("1");
        for  (int i=key.length() -1; i >= 0; i--) {
            BigInteger letter = new BigInteger(String.valueOf(key.charAt(i) - 96));
            hashVal = hashVal.add(letter.multiply(pow27));
            pow27 = pow27.multiply(new BigInteger(String.valueOf(27))) ;
        }
        return hashVal.mod(new BigInteger(String.valueOf(arr.length))).intValue();
    }


}
